package com.example.video.controller;

import com.example.video.constant.SystemConstant;
import com.example.video.service.VideoMaterialService;
import com.example.video.util.FileToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

/**
 * @ClassName VideoController
 * @Description TODO
 * @Author Jason
 * @Date 2019/1/21 10:05
 * @Version 1.0
 **/
@Slf4j
@Controller
@RequestMapping("/video")
public class VideoController {

    @GetMapping("/")
    public String video(){
        return "video";
    }
    @GetMapping("/upload")
    public String upload(){
        return "video-upload";
    }
    @Autowired
    private VideoMaterialService videoMaterialService;
    /**
     * 播放加密MP4
     * @param response
     * @throws IOException
     */
    @RequestMapping("/playMp4")
    @ResponseBody
    public void playMp4(HttpServletResponse response, String fileName) throws IOException {

      // TODO 测试联调结束后需删除
      //  fileName = "edu/video/6689AC1A506133C13FDA593135E2D923.mp4";
        String tempFilePath = SystemConstant.VIDEO_TEMP_PATH + fileName;

        try {
            // 解密过后的临时文件路径
            tempFilePath = videoMaterialService.decryptVideo(fileName);

            FileInputStream inputStream = new FileInputStream(tempFilePath);

            byte[] data = FileToolUtil.inputStreamToByte(inputStream);
            String diskfilename = "final.mp4";
            response.setContentType("video/mp4");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
            System.out.println("data.length " + data.length);
            response.setContentLength(data.length);
            //response.setHeader("Access-Control-Allow-Origin","*");
            response.setHeader("Content-Range", "" + Integer.valueOf(data.length-1));
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Etag", "W/\"9767057-1323779115364\"");
            OutputStream os = response.getOutputStream();

            os.write(data);
            //先声明的流后关掉！
            os.flush();
            os.close();
            inputStream.close();

        }catch (Exception e){
            log.error("play video error ...", e);
        }finally {
            videoMaterialService.deleteVideoFile(tempFilePath);
        }

    }


    @RequestMapping("/upload")
    public String springUpload(CommonsMultipartResolver multipartResolver, HttpServletRequest request) throws IllegalStateException, IOException {
        long startTime = System.currentTimeMillis();

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        multipartResolver.setServletContext(request.getSession().getServletContext());

        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {

            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();

            while (iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {

                    // 创建上传的目录
                    String path = SystemConstant.VIDEO_UPLOAD_PATH;
                    if (!new File(path).isDirectory()) {
                        new File(path).mkdirs();
                    }

                    String fileName = file.getOriginalFilename();
                    path = path + fileName;
                    file.transferTo(new File(path));
                    // 加密
                    videoMaterialService.encryptVideo(fileName);
                }
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("upload file cost time ：{}ms" , String.valueOf(endTime - startTime));
        return "video";
    }
}
